package com.wei.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wei.blog.common.dto.BlogPage;
import com.wei.blog.common.help.UserHelp;
import com.wei.blog.common.status.BlogStatus;
import com.wei.dao.CommentDao;
import com.wei.entity.CommentEntity;
import com.wei.service.CommentService;
import com.wei.service.ILikeService;
import com.wei.vo.CommentVo;
import com.wei.vo.LikeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("CommentService")
public class CommentServiceImpl extends ServiceImpl<CommentDao, CommentEntity> implements CommentService {

    @Autowired
    private UserHelp userHelp;

    @Autowired
    private ILikeService likeService;

    @Override
    public BlogPage<CommentVo> getCommentListByTid(BlogPage<CommentVo> page, Integer id) {
        //查询以一级评论（对帖子的评论）
        page = baseMapper.selectCommentListTid(page, id, BlogStatus.TOPIC_COMMENT.getCode());
        BlogPage newReplyPage= new BlogPage();
        LikeVo likeVo = new LikeVo();
        likeVo.setEntityType(2);
        if (userHelp.get()!=null){
            likeVo.setUserId(userHelp.get().getUid());
        }
        //查看二级评论 对评论的回复
        List<CommentVo> records = page.getRecords();
        for (CommentVo comment : records) {
            //循环一级评论 查看二级评论
            likeVo.setEntityId(comment.getCommentEntity().getId());
            //查询一级评论的点赞信息
            findCommentLikeInfo(comment,likeVo);

            //查询某一个一级评论的所有二级评论
            Integer cid = comment.getCommentEntity().getId();
            Page<CommentVo> replyPage = baseMapper.selectCommentListTid(
                    newReplyPage,
                    cid,
                    BlogStatus.TOPIC_REPLY.getCode()
                    );
            List<CommentVo> records1 = replyPage.getRecords();
            //查询二级的点赞数量和点赞状态
            for (CommentVo commentVo : records1) {
                //设置二级评论的id
                likeVo.setEntityId(commentVo.getCommentEntity().getId());
            }
            //给一级评论设置二级评论信息
            comment.setReplyList(records1);
        }
        return page;
    }

    @Override
    public Long getCommentCountByTopicId(Integer type, Integer id) {
        return baseMapper.getCommentCountByTopicId(type,id);
    }

    public void findCommentLikeInfo(CommentVo comment,LikeVo likeVo){
        //查询评论的点赞数量 和 点赞状态（当前用户是否点赞）
        comment.setLikeCount(likeService.likeCount(likeVo));
        if (likeVo.getUserId()!=null){
            comment.setLikeStatus(likeService.likeStatus(likeVo)?1:0);
        }
    }

}
